﻿using DevelopAssistant.Service;
using ICSharpCode.WinFormsUI.Controls;
using ICSharpCode.WinFormsUI.Controls.NTimeLine;
using ICSharpCode.WinFormsUI.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DevelopAssistant.Core
{
    public partial class StartForm : Form
    {
        #region 动画窗体调用
        //动画窗体调用
        [DllImport("user32")]
        private static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);
        const int AW_HOR_POSITIVE = 0x0001;
        const int AW_HOR_NEGATIVE = 0x0002;
        const int AW_VER_POSITIVE = 0x0004;
        const int AW_VER_NEGATIVE = 0x0008;
        const int AW_CENTER = 0x0010;
        const int AW_HIDE = 0x10000;
        const int AW_ACTIVATE = 0x20000;
        const int AW_SLIDE = 0x40000;
        const int AW_BLEND = 0x80000;
        //动画窗体调用
        #endregion

        int radius = 2;

        TodoManager.ITodoService service = new TodoManager.TodoServiceImpl();

        private int _totoLimitCount;
        public int TodoLimitCount
        {
            get { return _totoLimitCount; }
        }

        private int _todoTotalCount;
        public int TodoTotalCount
        {
            get
            {
                return _todoTotalCount;
            }
        }

        private List<MonthItem> _todoList;
        public List<MonthItem> TodoList
        {
            get
            {
                return _todoList;
            }
        }

        public new Rectangle WorkArea
        {
            get
            {
                Rectangle rectangle = new Rectangle();
                rectangle = Screen.FromPoint(Cursor.Position).WorkingArea;
                return rectangle;
            }
        }

        public StartForm()
        {
            InitializeComponent();
            InitializeControls();
        }

        private void InitializeControls()
        {
            this.Font = new Font("宋体", 10.0f);
            this.ControlBox = false;                      
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
            this.FormBorderStyle = FormBorderStyle.None;

            int DefaultTextFontSize = 10;
            string DefaultTextFontName = "微软雅黑";
            if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DefaultTextFontSize"] + ""))
            {
                DefaultTextFontSize = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["DefaultTextFontSize"] + "");
            }
            if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DefaultTextFontName"] + ""))
            {
                DefaultTextFontName = System.Configuration.ConfigurationManager.AppSettings["DefaultTextFontName"] + "";
            }
            AppSettings.ToolStripMenuFont = new Font(DefaultTextFontName, DefaultTextFontSize);
            ICSharpCode.WinFormsUI.Controls.NToolStripItemTheme.TextFont = AppSettings.ToolStripMenuFont;
        }

        private void StartForm_Load(object sender, EventArgs e)
        {
            this.SetBoundsCore(WorkArea);
            AnimateWindow(this.Handle, 300, AW_HOR_NEGATIVE | AW_CENTER);
            backgroundWorker1.RunWorkerAsync();
        }

        public void SetBoundsCore(Rectangle rec)
        {
            int x = rec.X + (rec.Width - this.Width) / 2;
            int y = rec.Y + (rec.Height - this.Height) / 2;
            this.SetBoundsCore(x, y, this.Width, this.Height, BoundsSpecified.All);
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int total = 0;
            int limit = AppSettings.TodoLimit;
            var list = service.QueryTodoMonthList(limit, out total);

            List<MonthItem> MonthList = new List<MonthItem>();
            foreach (TodoManager.TodoDTO Dto in list)
            {
                string MonthName = Dto.YearMonth;
                MonthItem monthItem = new MonthItem();
                monthItem.Name = MonthName;
                monthItem.Date = Convert.ToDateTime(Dto.YearMonth + "-01");
                monthItem.DateLabel = DateTimeUtils.ToDateLabel(monthItem.Date);

                List<DateItem> DateList = new List<DateItem>();

                var sublist = service.QueryTodoDateList(limit, Dto.YearMonth);

                foreach (TodoManager.TodoDTO DateDto in sublist)
                {
                    string DateName = Convert.ToDateTime(DateDto.DateTime).ToString("yyyy-MM-dd");
                    DateItem DateItem = new DateItem();
                    DateItem.Date = DateDto.DateTime.Value;

                    List<DateTimeItem> DateTimeList = new List<DateTimeItem>();

                    var subsublist = service.QueryTodoDateTimeList(limit, Dto.YearMonth, DateDto.DateTime.Value.ToString("yyyy-MM-dd"));

                    foreach (TodoManager.TodoDTO DateTimeDto in subsublist)
                    {
                        DateTimeItem DateTimeItem = new DateTimeItem();

                        DateTimeItem.Id = DateTimeDto.ID.ToString();
                        DateTimeItem.Name = DateTimeDto.Name;
                        DateTimeItem.Title = DateTimeDto.Name;
                        DateTimeItem.ToolTip = DateTimeDto.Title;
                        DateTimeItem.Timeliness = (Timeliness)Enum.Parse(typeof(Timeliness), DateTimeDto.Timeliness.ToString());
                        DateTimeItem.Summary = DateTimeDto.Summary;
                        DateTimeItem.DateTime = Convert.ToDateTime(DateTimeDto.DateTime);
                        DateTimeItem.ResponsiblePerson = DateTimeDto.ResponsiblePerson;
                        DateTimeItem.PersonName = GetShowPersonName(DateTimeDto.ResponsiblePerson);

                        DateTimeList.Add(DateTimeItem);
                    }

                    DateItem.List = DateTimeList;

                    DateList.Add(DateItem);
                }

                monthItem.List = DateList;

                MonthList.Add(monthItem);
            }

            _todoList = MonthList;
            _totoLimitCount = limit < total ? limit : total;
            _todoTotalCount = total;

            AppSettings.ScheduleTasks = service.GetScheduleTasks("");

            int delay = 2 * 1000;

            System.Threading.Thread.Sleep(delay);
        }

        private string GetShowPersonName(string ResponsiblePerson)
        {
            string result = "";
            if (AppSettings.TodoShowName && !string.IsNullOrEmpty(ResponsiblePerson))
            {
                result = ResponsiblePerson.Substring(ResponsiblePerson.Length - 1);
            }
            return result;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }

        private void StartForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            AnimateWindow(this.Handle, 200, AW_CENTER + AW_VER_NEGATIVE + AW_HIDE);
        }

        private void SetWindowRegion()
        {
            //Rectangle rect = new Rectangle(0, radius, this.Width, this.Height - 2 * radius);
            Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
            System.Drawing.Drawing2D.GraphicsPath FormPath = GetRoundedRectPath(rect, (int)(radius * 1.0));
            this.Region = new Region(FormPath);
        }

        protected override void OnResize(System.EventArgs e)
        {
            SetWindowRegion();
        }

        private GraphicsPath GetRoundedRectPath(Rectangle rect, int radius)
        {
            int diameter = radius;
            Rectangle arcRect = new Rectangle(rect.Location, new Size(diameter, diameter));
            GraphicsPath path = new GraphicsPath();
            //   左上角  
            path.AddArc(arcRect, 180, 90);
            //   右上角   
            arcRect.X = rect.Right - diameter;
            path.AddArc(arcRect, 270, 90);
            //   右下角  
            arcRect.Y = rect.Bottom - diameter;
            path.AddArc(arcRect, 0, 90);
            //   左下角   
            arcRect.X = rect.Left;
            path.AddArc(arcRect, 90, 90);
            path.CloseFigure();
            return path;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
            System.Drawing.Drawing2D.GraphicsPath FormPath = GetRoundedRectPath(rect, (int)(radius * 1.0));
            Graphics graphic = e.Graphics;
            graphic.DrawPath(new Pen(new SolidBrush(_xtheme.FormBorderOutterColor), 2.0f), FormPath);
        }

        private ICSharpCode.WinFormsUI.Theme.WinFormsUIThemeBase _xtheme;
        public ICSharpCode.WinFormsUI.Theme.WinFormsUIThemeBase XTheme
        {
            set
            {
                if (value != null)
                    _xtheme = value.CloneThemeBase();                
                _xtheme.ShowShadow = false;                
            }
            get { return _xtheme; }
        }
        
    }
}
